<template>
  <div>
    <div class="content-container" ref="chatContent">
      <!-- 消息整体-->
      <div
        :class="
          message.sender === 'me' ? 'chat-message-me' : 'chat-message-other'
        "
        :style="{
          'padding-bottom': messages.length - 1 === index ? '2rem' : 'none',
        }"
        v-for="(message, index) in messages"
        :key="index"
      >
        <!--消息头像-->
        <div
          :class="
            message.sender === 'me'
              ? 'message-me-asWhole-headPortrait'
              : 'message-other-asWhole-headPortrait'
          "
        >
          <img
            v-if="message.sender === 'me'"
            src="~@/assets/examineeFace.png"
            class="examineeFace_logo_style"
          />
          <img
            v-if="message.sender === 'other'"
            src="~@/assets/aiFace.png"
            class="examineeFace_logo_style"
          />
        </div>
        <!--消息-->
        <div
          :class="
            message.sender === 'me'
              ? 'message-me-asWhole-right'
              : 'message-other-asWhole-right'
          "
        >
          <!--消息上面-->
          <div
            :class="
              message.sender === 'me'
                ? 'message-me-asWhole-top'
                : 'message-other-asWhole-top'
            "
          >
            {{ message.sender === "me" ? "我" : "王阳明" }}
          </div>
          <!--消息内容-->
          <div
            :class="message.sender === 'me' ? 'message-me' : 'message-other'"
          >
            {{ message.content }}
          </div>
        </div>
      </div>
    </div>
    <div class="input-container">
      <div style="height: 10vh; text-align: center">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入内容"
          style="width: 95vw"
          v-model="info"
        >
        </el-input>

        <el-button
          style="float: right; margin-top: 20px; margin-right: 5vw"
          @click="addMessage"
          type="primary"
          round
          >发送</el-button
        ><el-button
          style="float: right; margin-top: 20px; margin-right: 5vw"
          @click="CreateNewConversation"
          type="plain"
          round
          >新对话</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
var baseUrl = "http://1.12.241.171:8083";
export default {
  data() {
    return {
      info: "",
      messages: [
        { sender: "other", content: "吾乃阳明，今日与汝共探心学之妙。" },
      ],
      clientId: "123",
    };
  },
  methods: {
    addMessage() {
      this.messages.push({ sender: "me", content: this.info });
      this.getAITalk();
    },
    CreateNewConversation() {
      this.messages = [
        { sender: "other", content: "吾乃阳明，今日与汝共探心学之妙。" },
      ];
      fetch(`${baseUrl}/Chat/NewSseChat`);
    },
    async getAITalk() {
      let _this = this;
      if (typeof EventSource !== "undefined") {
        // 检查浏览器是否支持SSE
        var source = new EventSource(
          `${baseUrl}/Chat/createSseConnect?clientId=${_this.clientId}`
        );
        source.onopen = function (event) {
          console.log("onopen", event);
          _this.messages.push({ sender: "other", content: "..." });
          let _info = _this.info;
          _this.info = "";
          fetch(
            `${baseUrl}/Chat/SseChat?content=${_info}&clientId=${_this.clientId}`
          );
        };

        source.onmessage = function (event) {
          // 当接收到消息时执行
          if (
            _this.messages[_this.messages.length - 1].content.indexOf("...") ==
            0
          ) {
            _this.messages[_this.messages.length - 1].content = "";
          }
          let resData = event.data;
          console.log("Message received: ", event.data);
          let stopFlag = false;
          if (
            resData != "" &&
            resData != null &&
            resData.indexOf("message.completed") > 0
          ) {
            stopFlag = true;
            console.log(resData);
            console.log("stopFlag", stopFlag);
          }
          if (resData.startsWith("data:")) {
            let content = JSON.parse(resData.replace("data:", "")).content;
            let type = JSON.parse(resData.replace("data:", "")).type;
            if (
              content != null &&
              type != "follow_up" &&
              type != "verbose" &&
              content.length < 10
            ) {
              _this.messages[_this.messages.length - 1].content += content;
            }
            if (resData.replace("data:", "").indexOf("DONE") > 0) {
              console.log(resData);
              source.close();
              _this.messages[_this.messages.length - 1].content += " over";
            }
            _this.scrollToBottom();
          }
        };
      } else {
        // 浏览器不支持SSE
        console.log(
          "Sorry, your browser does not support server-sent events..."
        );
      }
    },

    scrollToBottom() {
      this.$nextTick(() => {
        this.$refs.chatContent.scrollTop = this.$refs.chatContent.scrollHeight;
      });
    },
  },
};
</script>

<style>
body {
  margin: 0 !important;
}
.content-container {
  height: 74vh;
  overflow: auto;
  padding-top: 6vh;
}
.input-container {
  height: 17vh;
  margin-top: 3vh;
}
.chat-message-other {
  /*background-color: red;*/
  display: flex;
  padding-left: 1rem;
  padding-top: 1rem;
}

.chat-message-me {
  /*background-color: red;*/
  display: flex;
  padding-right: 1rem;
  padding-top: 1rem;
  flex-direction: row-reverse; /* 将子div的顺序反转 */
}

.message-me-asWhole-headPortrait {
  padding: 3px;
}

.message-other-asWhole-headPortrait {
  padding: 3px;
}

.message-me-asWhole-right {
  display: flex;
  flex-direction: column; /* 设置子元素垂直排列 */
  margin-left: 0.1rem;
}

.message-other-asWhole-right {
  display: flex;
  flex-direction: column; /* 设置子元素垂直排列 */
  margin-left: 0.1rem;
}

.message-me-asWhole-top {
  padding: 3px;
  /* font-size: 12px; */
  font-family: 微软雅黑;
  padding: 3px;
  color: rgba(134, 144, 156, 1);
  text-align: right;
}

.message-other-asWhole-top {
  padding: 3px;
  /* font-size: 12px; */
  font-family: 微软雅黑;
  padding: 3px;
  color: rgba(134, 144, 156, 1);
}

.message-me {
  background-color: rgba(242, 243, 245, 1);
  max-width: 280px;
  word-wrap: break-word; /* 处理英文单词换行 */
  word-break: break-all; /* 处理中文换行 */
  display: inline-block; /*将div元素转换为行内块元素*/
  width: auto; /* 宽度根据文本宽度自动调正*/
  padding: 6px 12px;
  border-radius: 4px;
}

.message-other {
  background-color: rgba(242, 243, 245, 1);
  max-width: 280px;
  word-wrap: break-word; /* 处理英文单词换行 */
  word-break: break-all; /* 处理中文换行 */
  display: inline-block; /*将div元素转换为行内块元素*/
  width: auto; /* 宽度根据文本宽度自动调正*/
  padding: 6px 12px;
  border-radius: 4px;
}

.examineeFace_logo_style {
  width: 30px;
}
</style>
